<?php

namespace App\Http\Controllers\Api;

use App\Constants\CodeResponse;
use App\Exceptions\BusinessException;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegCodeRequest;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\ResetCodeRequest;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

class AuthController extends ApiController
{
    /**
     * 用户注册
     * @param  RegisterRequest  $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function register(RegisterRequest $request): JsonResponse
    {
        // 接收参数
        $username = $request->post('username');
        $password = $request->post('password');
        $mobile = $request->post('mobile');
        $code = $request->post('code');
        // 验证短信验证码是否正确
        UserService::getInstance()->checkCaptcha($mobile,$code,'register_captcha_');
        // 数据写入数据库
        $user = new User();
        $user->username = $username;
        $user->password = Hash::make($password);
        $user->mobile = $mobile;
        $user->avatar = 'https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64';
        $user->nickname = $username;
        $user->last_login_time = now()->toDateTimeString();
        $user->last_login_ip = $request->getClientIp();
        $user->save();

        return $this->success([
            'token' => '$token',
            'userInfo' => [
                'nickName' => $username,
                'avatarUrl' => $user->avatar
            ]
        ]);
    }

    /**
     * 获取短信验证码
     * @param  RegCodeRequest  $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function regCode(RegCodeRequest $request): JsonResponse
    {
        $mobile = $request->post('mobile');
        // 一分钟内只能请求一次
        $lock = Cache::add('register_captcha_lock_'.$mobile,1,60);
        if (!$lock) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY);
        }
        UserService::getInstance()->checkMobileCaptchaCount($mobile);
        $code = UserService::getInstance()->setCaptcha($mobile,'register_captcha_');
        //发送短信验证码
        UserService::getInstance()->sendCaptchaMessage($mobile,$code);
        return $this->success();
    }

    /**
     * 用户登陆
     * @param  LoginRequest  $request
     * @return JsonResponse
     */
    public function login(LoginRequest $request): JsonResponse
    {
        $username = $request->post('username');
        $password = $request->post('password');
        // 获取用户信息
        $user = UserService::getInstance()->getByUsername($username);
        if (is_null($user)) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT);
        }
        // 校验密码
        $isPass = Hash::check($password,$user->getAuthPassword());
        if (!$isPass) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT,'账号或密码错误');
        }
        // 更新登陆用户信息
        $user->last_login_time = now()->toDateTimeString();
        $user->last_login_ip = $request->getClientIp();
        if (!$user->save()) {
            return $this->fail(CodeResponse::UPDATED_FAIL);
        }
        $token = Auth::guard('wx')->login($user);
        return $this->success([
            'token' => $token,
            'userInfo' => [
                'nickName' => $username,
                'avatarUrl' => $user->avatar
            ]
        ]);
    }

    /**
     * 获取登陆用户信息
     * @return JsonResponse
     */
    public function info(): JsonResponse
    {
        $user = Auth::guard('wx')->user();
        return $this->success([
            'nickName' => $user->nickname,
            'avatar' => $user->avatar,
            'gender' => $user->gender,
            'mobile' => $user->mobile
        ]);
    }

    /**
     * 推出登陆
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        Auth::guard('wx')->logout();
        return $this->success();
    }

    public function reset(ResetCodeRequest $request)
    {
        $mobile = $request->post('mobile');
        $code = $request->post('code');
        // 验证短信验证码是否正确
        UserService::getInstance()->checkCaptcha($mobile,$code,'reset_captcha_');
        // 根据手机号查找用户信息


    }

    /**
     * 重置密码发送短信验证码
     * @param  ResetCodeRequest  $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function captcha(ResetCodeRequest $request): JsonResponse
    {
        $mobile = $request->post('mobile');
        // 一分钟内只能请求一次
        $lock = Cache::add('register_captcha_lock_'.$mobile,1,60);
        if (!$lock) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY);
        }
        UserService::getInstance()->checkMobileCaptchaCount($mobile);
        $code = UserService::getInstance()->setCaptcha($mobile,'reset_captcha_');
        //发送短信验证码
        UserService::getInstance()->sendCaptchaMessage($mobile,$code);
        return $this->success();
    }

    /**
     * 修改个人信息
     * @param  Request  $request
     * @return JsonResponse
     */
    public function profile(Request $request): JsonResponse
    {
        $user = Auth::guard('wx')->user();
        $avatar = $request->post('avatar');
        $gender = $request->post('gender');
        $nickname = $request->post('nickname');
        if(!empty($avatar)) {
            $user->avatar = $avatar;
        }
        if (!empty($gender)) {
            $user->gender = $gender;
        }
        if (!empty($nickname)) {
            $user->nickname = $nickname;
        }

        $ret = $user->save();
        if($ret) {
            return $this->success();
        }
        return $this->fail(CodeResponse::UPDATED_FAIL);
    }
}